package com.xhai.common.utils.encrypt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Date;
import java.util.Map;

/**
 * @author xhai
 * @description jwt工具类
 * @date 2025/6/7
 */
@Component
public class JwtUtils {

    // 有效期（分钟）
    private static Integer JWT_TTL;

    // 密钥
    private static String JWT_KEY;

    private static SecretKey SECRET_KEY;

    public JwtUtils(@Value("${admin.jwt.expire-time}") Integer expireTime, @Value("${admin.jwt.secret-key}") String secretKey) {
        this.JWT_TTL = expireTime;
        this.JWT_KEY = secretKey;
        this.SECRET_KEY = Keys.hmacShaKeyFor(JWT_KEY.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 解析jwt
     *
     * @param jwt
     * @return
     */
    public static Claims parseJWT(String jwt) {
        return Jwts.parser()
                .verifyWith(SECRET_KEY)
                .build()
                .parseSignedClaims(jwt)
                .getPayload();
    }

    /**
     * 生成jwt
     *
     * @param claims
     * @return
     */
    public static String createToken(Map<String, Object> claims) {
        Instant now = Instant.now();
        Instant expiration = now.plusMillis(JWT_TTL * 60 * 1000);

        String token = Jwts.builder()
                .claims(claims)
                .issuedAt(Date.from(now))
                .expiration(Date.from(expiration))
                .signWith(SECRET_KEY)
                .compact();
        return token;
    }
}
